<script setup>
import {defineEmits, inject, nextTick, onMounted, reactive, watch} from "vue";
import {ElMessage} from "element-plus";
// import * as L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import L from "leaflet";
import request from "../../utils/request.js";
import homeIcon from '../../assets/icon-camera.png'

const emit = defineEmits(["changeAreaData"]);

let map = reactive({});
const $axios = inject("$axios");

const props = defineProps({
    mapData: Object,
    lonOrlat: Object,
});

watch(props.mapData, (n, v) => {
    getBackHomeCount();
});

watch(props.lonOrlat, (n, v) => {
    loadCameras();
})

// 定义汇总信息数据
const tableData = reactive([]);

// 获取汇总信息数据
function getBackHomeCount() {
    tableData.splice(0, tableData.length);
    $axios
        .get("/api/overview/overview", {
            params: {
                areaCode: props.mapData.areaCode,
            },
        })
        .then((res) => {
            console.log('汇总信息', res)
            tableData.push({
                gridManagers: res.data.data.gridManagers,
                grids: res.data.data.grids,
                houses: res.data.data.houses,
                persons: res.data.data.persons,
                streets: res.data.data.streets,
                villages: res.data.data.villages,
            });
        })
        .then(nextTick);
}

function init() {
    //加载区县GEO-JSON
    request.get("/api/geo/selectByAreaCode").then((resp) => {
        let geojson = resp.data.data;
        initMap(geojson); //初始化地图
        loadCameras('');
    });
}

let cameraLayers = null;

function loadCameras(areaCode) {
    return;
    //地图未初始化
    if (!map) {
        return;
    }
    //用于存放视频设备图标的图层组
    if (!cameraLayers) {
        cameraLayers = L.layerGroup().addTo(map);
    } else {
        cameraLayers.removeAll(); //如果已经有设备图标，则清空
    }

    //图标
    let cameraIcon = L.icon({
        iconUrl: homeIcon,
        iconSize: [40, 40],
    });

    props.lonOrlat.forEach((item) => {
        item.devices.forEach((item1) => {
            L.marker([item1.latitude, item1.longitude], {
                icon: cameraIcon,
            }).addTo(cameraLayers);
        });
    });

}

function initMap(geojson) {
    //中心点
    let center = [geojson[0].centerLat, geojson[0].centerLon];
    //创建地图
    map = L.map('leaflet-map-1', {
        center: center, //中心点
        zoom: 10, //初始放大系数
        crs: L.CRS.EPSG4326 //wsg84坐标系
    });
    //地区图层组
    let areaLayer = L.layerGroup();
    map.addLayer(areaLayer);
    //区县
    for (let i = 1; i < geojson.length; i++) {
        let geoObject = JSON.parse(geojson[i].geoJson); //服务端返回的是字符串JSON，转换为对象
        //创建一个geoJSON图层加入到地区图层组
        let layer = L.geoJSON(geoObject, {
            onEachFeature: function (feature, layer) {
                layer.options.color = '#A2EEFF' //边框颜色
                layer.options.weight = 1 //边框宽度
                layer.options.fillColor = '#42DFFC'; //填充色
                layer.options.fillOpacity = 0.4;//半透明
            }
        });
        //将当前区县加入区县图层组
        areaLayer.addLayer(layer);
        /**
         * 在地图上做标记，因为标记有特殊背景，因此使用DivIcon
         */
            //地图标记的标注图标
        let icon = L.divIcon({
                className: 'marker-div-icon',
                html: geojson[i].name,
                iconAnchor: [30, 50] //偏移量，尽量调整到区县的中间
            });
        //标记的坐标
        let markerPos = [geojson[i].centerLat, geojson[i].centerLon];
        //创建标记，加入地图，绑定事件
        L.marker(markerPos, {
            icon: icon,
            riseOnHover: false
        }).addTo(map)
            .on('click', function () {//Marker事件
                console.log(geojson[i]);
                emit("changeAreaData", geojson[i]);
            })
    }

    let villageLayer = L.layerGroup().addTo(map);

    //风险地点列表
    let iconVillage = L.icon({
        iconUrl: 'https://assets.honqun.cn/assets/location.png',
        iconSize: [36, 36]
    });
    request.get("/api/overview/listRiskLocationDetails").then((resp) => {
        let villages = resp.data.data;
        for (let i = 0; i < villages.length; i++) {
            let names = [];
            let point = [villages[i].lat, villages[i].lon]
            for (let j = 0; j < villages[i].patients.length; j++) {
                names.push('<div style="padding:5px 3px;float:left;width:30%">' + villages[i].patients[j] + '</div>')
            }
            L.marker(point, {
                icon: iconVillage,
                zIndexOffset: 100,
                riseOnHover: true
            }).addTo(villageLayer)
                .bindPopup('<div style="color: #ee5108;font-weight: 700;padding:10px 0">' + villages[i].village + '（' + villages[i].patients.length + '人）</div>'
                    + '<div style="width: 300px;">'
                    + names.join('')
                    + '<div style="clear: both"></div>'
                    + '</div>')
        }
    })

}

function getPersonInfo() {

}

function colorGen() {
    const colors = [
        "rgba(0, 234, 255, 1)",
        "rgba(49, 235, 157, 1)",
        "rgba(255, 210, 0, 1)",
        "rgba(255, 138, 0, 1)",
    ];
    let index = 0;

    function* gen() {
        while (true) {
            console.log(index);
            if (index > 3) {
                index = 0;
            }
            yield colors[index];
            index++;
        }
    }

    return gen();
}

function handleoldCityDistrictClick() {
    ElMessage({
        showClose: true,
        message: "老城区人口10.5万人.",
    });
}

const list = reactive([]);

onMounted(() => {
    getBackHomeCount();
    getPersonInfo();
    init();
});
</script>

<template>
    <div class="mapHeader">
        <div class="headerItem">
            <div class="top-box">
                <img src="@/assets/m1.png"/>
                <div>
                    <div>
            <span style="font-size: 14px; color: #00EAFF">
              {{ tableData[0]?.streets }}
            </span>
                        <span style="font-size: 12px">个</span>
                    </div>
                    <div style="font-size: 12px">街道</div>
                </div>
            </div>
        </div>
        <div class="headerItem">
            <div class="top-box">
                <img src="@/assets/m2.png"/>
                <div>
                    <div>
            <span style="font-size: 14px; color: #FFD200">
              {{ tableData[0]?.villages }}
            </span>
                        <span style="font-size: 12px">个</span>
                    </div>
                    <div style="font-size: 12px">村(社区)</div>
                </div>
            </div>
        </div>
        <div class="headerItem">
            <div class="top-box">
                <img src="@/assets/m3.png"/>
                <div>
                    <div>
            <span style="font-size: 14px; color: #08FD77">
              {{ tableData[0]?.grids }}
            </span>
                        <span style="font-size: 12px">个</span>
                    </div>
                    <div style="font-size: 12px">网格数</div>
                </div>
            </div>
        </div>
        <div class="headerItem">
            <div class="top-box">
                <img src="@/assets/m4.png"/>
                <div>
                    <div>
            <span style="font-size: 14px; color: #FF8A00">
              {{ tableData[0]?.gridManagers }}
            </span>
                        <span style="font-size: 12px">个</span>
                    </div>
                    <div style="font-size: 12px">网格员数</div>
                </div>
            </div>
        </div>
        <div class="headerItem">
            <div class="top-box">
                <img src="@/assets/m5.png"/>
                <div>
                    <div>
            <span style="font-size: 14px; color: #F95352">
              {{ tableData[0]?.houses }}
            </span>
                        <span style="font-size: 12px">户</span>
                    </div>
                    <div style="font-size: 12px">全县户数</div>
                </div>
            </div>
        </div>
        <div class="headerItem">
            <div class="top-box">
                <img src="@/assets/m6.png"/>
                <div>
                    <div>
            <span style="font-size: 14px; color: #08FD77">
              {{ tableData[0]?.persons }}
            </span>
                        <span style="font-size: 12px">人</span>
                    </div>
                    <div style="font-size: 12px">全县人口数</div>
                </div>
            </div>
        </div>
    </div>
    <div id="map-1" style="margin-top: 30px; height: 500px; padding: 20px">
        <div id="leaflet-map-1"></div>

    </div>
</template>
<style>
body .leaflet-control {
    opacity: 0.1;
}

body .marker-div-icon {
    width: 60px !important;
    height: 50px !important;
    background: url("../../assets/marker-1.png") no-repeat;
    background-size: 100% 100%;
    padding-top: 7px;
    text-align: center;
    color: #00f9ff;
}

body .marker-div-icon:hover {
    background: url("../../assets/marker-2.png") no-repeat;
    background-size: 100% 100%;
    color: #FCEE4F;
}

</style>
<style lang="less" scoped>
.mapHeader {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    background-color: rgba(5, 69, 119, 0.43);
    height: 54px;
    border: 1px solid rgba(2, 204, 212, 0.4);
    box-shadow: 4px 4px 5px rgba(32, 72, 133, 1);

    .headerItem {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: white;
        text-align: center;
    }
}

.cls-1 {
    fill: #0071bc;
    stroke: #00f9ff;
    stroke-linecap: square;
    stroke-miterlimit: 10;
    stroke-width: 2px;
}

h3 {
    color: #fff;
    margin: 0 auto;
    margin-top: 20px;
    margin-bottom: 20px;
}

#leaflet-map-1 {
    height: 50vh;
    margin-top: -5vh;
    // border: 1px solid #409eff;
}

.leaflet-container {
    background-color: transparent;
}

.top-box {
    display: flex;
    align-items: center;
}

.top-box > img {
    width: 30px;
}
</style>
